--
-- Author: ping.wang
-- Date: 2019-06-25 14:37:13
--
-- RewardWelfareHeroTreasurePanel
--

local ClassRef = app.mvc.createPanelClass(...)
local string_split = string.split
local string_format = string.format
local ListViewHorizontal = require("app.widget.listview.ListViewHorizontal")
local RewardHeroTreasureRender = import(".renders.RewardHeroTreasureRender")
local FRAME_MAX = 30 --播放动画 最多30帧 一次进度条播完
local FRAME_MIN = 15 --播放动画 最少15帧 一次进度条播完
local frame = 0
local frameExp = 0 --计算出每帧增加的经验
local frameMax = 0
local maxExp = 0
local curExp = 0
local targetExp = 0
--data =
function ClassRef.createWithData(data, node)
    local sprite = ClassRef.extend(node or cc.CSLoader:createNode(Res.RewardWelfareHeroTreasure))
    if node == nil then
        ccui.Helper:doLayout(sprite)
    end
    sprite:init(data)
    return sprite
end
function ClassRef.create(node)
    return ClassRef.createWithData(nil, node)
end

--
function ClassRef:init(data)
    self.super.init(self, data)
    self._coin = nil

    self._tips2 = self._ui.Panel_bom:findChild("tips_2")

    self._ui.Panel_money:setTouchEnabled(true)
    self._ui.Panel_money:addClickEventListener(handler(self, self._showMoneyTips))
    self._ui.Button_plus:setVisible(true)
    --添加货币
    self._ui.Button_plus:addClickEventListener(function()
        if UIHandler:isFunctionOpen(Constant.FUNC_TYPE_SHOP) and self._coin then
            app:sendMsg("MallController", "buyGameRes", self._coin:getId())
        end
    end)

    --规则说明
    self._ui.Panel_top:findChild("btn_tips"):addClickEventListener(function()
        executeFunc(self._onOperate,"showHeroTreasureDes")
    end)

    --title
    self._ui.Panel_date:findChild("Panel_tlt/tips_1"):setString(L("免费"))
    self._goldenTitle = self._ui.Panel_date:findChild("Panel_tlt/tips_2")

    local params = {
        renderClass = RewardHeroTreasureRender,
        perNum = 1,
        cellEventProxy = function(eventName, data)
            if eventName == "heroTreasureStartGetAward" then
                data.activityUID = self._data:getUID()
                executeFunc(self._onOperate, eventName, data)
            else
                executeFunc(self._onOperate, eventName, data)
            end
        end,
    }

    self._productListnode = ListViewHorizontal.new( self._ui.Panel_date:findChild("ScrollView"), params )

    self._ui.Panel_bom:findChild("Button_enter"):addClickEventListener(
        function()
            if self._data then
                if self._data:hasBuyGolden() then
                    --如果已经购买过 则显示购买活跃经验的界面
                    executeFunc(self._onOperate,"openBuyHeroTreasureExpView", self._data)
                else
                    if self._coin then
                        executeFunc(self._onOperate,"openBuyHeroTreasureView",{type = 2,uid = self._data:getUID(), price = self._coin:getAmount(), itemId = self._coin:getId(),iconPath = self._coin:getIcon()})
                    end
                end
            end
        end
    )

    self._lvText = self._ui.Panel_top:findChild("num")
    self._progressBar = self._ui.Panel_top:findChild("Panel_bar/LoadingBar")
    self._expText = self._ui.Panel_top:findChild("Panel_bar/num")

    self:setContentSize( self._ui.Panel:getContentSize() )
    self:refresh()
end

function ClassRef:refresh()
    if self._data then
        self:setVisible( true )
        local data = self._data
        if not self._coin then
            local constConfig = data:getConstConfig()
            if constConfig then
                self._coin = UD:parseRewardToBagItem(constConfig.price)
                --第一次打开的时候初始化即可
                self:_setRichTextOnCost()
            else
                dump("不存在此活动activity_battlepass_total相关配置")
            end
        end
        --理论上data为RewardHeroTreasureVo

        if self._coin then
            self:initMoneyPanel(self._coin)
        end

        self:_initLvAndExp(self._data)

        self._ui.Panel_top:findChild("time"):setString(string.format(L("battlepass_string14"),data:getEndTimeDes()))

        if data:hasBuyGolden() then
            self._goldenTitle:setString(L("tips_3000411"))
            self._goldenTitle:setTextColor(cc.c3b(180,255,0))
            self._ui.Panel_bom:findChild("Button_enter/name"):setString(L("battlepass_string16"))
        else
            self._goldenTitle:setString(L("battlepass_string1"))
            self._goldenTitle:setTextColor(cc.c3b(236,101,101))
            self._ui.Panel_bom:findChild("Button_enter/name"):setString(L("ui_csd_1120"))
        end

        self._productListnode:reloadData(data:getAwardDataForList(),{startIndex = data:getFirstCanGetIdx()})

        local isMaxLv = data:getMaxLv() <= data:getCurLv()


        if self._data:hasBuyGolden() then

            if isMaxLv then
                self._ui.Panel_bom:findChild("tips_1"):setVisible(true)
                self._ui.Panel_bom:findChild("tips_3"):setVisible(false)
                self._ui.Panel_bom:findChild("tips_1"):setString(string.format(L("battlepass_string8"), self._data:getNextStartTimeDes()))
            else
                self._ui.Panel_bom:findChild("tips_1"):setVisible(false)
                self._ui.Panel_bom:findChild("tips_3"):setVisible(true)
                self._ui.Panel_bom:findChild("tips_3"):setString(L("battlepass_string6"))
            end
            self._tips2:setVisible(false)
        else
            self._ui.Panel_bom:findChild("tips_1"):setVisible(false)
            self._ui.Panel_bom:findChild("tips_3"):setVisible(false)
            self._tips2:setVisible(true)
        end

        if self._data:hasBuyGolden() then
            self._ui.Panel_bom:findChild("Button_enter"):setVisible(not isMaxLv)
        else
            self._ui.Panel_bom:findChild("Button_enter"):setVisible(true)
        end
        
    else
        self:setVisible( false )
    end
end

function ClassRef:onOperate(cb)
    self._onOperate = cb
end


function ClassRef:_initLvAndExp(data)
    local lastLv = data:getLastLv()
    local lastExp = data:getLastExp()
    local curLv = data:getCurLv()
    local curExp = data:getCurExp()

    if lastLv ~= curLv or lastExp ~= curExp then
        --需要显示动画
        local maxExp = data:getExpMaxByLv(lastLv)
        if maxExp and maxExp > 0 then
            self._lvText:setString(tostring(lastLv))
            self._progressBar:setPercent(lastExp/maxExp * 100)
            self._expText:setString(string_format("%d/%d",lastExp,maxExp))
            --然后要做动画 变成现在的经验以及等级
            --TODO 动画
            self:_showExpAnimation(data,lastExp,lastLv,curExp,curLv)
            data:setLastLvExpEqualCur()
        else
            dump("Error")
        end
    else
        local maxExp = data:getExpMaxByLv(curLv)
        if maxExp then
            self._lvText:setString(tostring(curLv))
            if maxExp > 0 then
                self._progressBar:setPercent(curExp/maxExp * 100)
                self._expText:setString(string_format("%d/%d",curExp,maxExp))
            else
                self._progressBar:setPercent(100)
                self._expText:setString("MAX")
            end
        end
    end
end

function ClassRef:_showExpAnimation(data, lastExp, lastLv, curExp, curLv)
    self._stepDatas = data:getLvDataForAnimation(lastExp, lastLv, curExp, curLv)
    self._step = 0
    self:nextStep()
    self:scheduleUpdate(handler(self, self.tick))
end

function ClassRef:stepOver()
    if self._stepDatas then
        local tmpData = self._stepDatas[#self._stepDatas]
        if tmpData.maxExp == 0 then
            self._lvText:setString(tostring(tmpData.lv))
            self._progressBar:setPercent(100)
            self._expText:setString("MAX")
        else
            self._lvText:setString(tostring(tmpData.lv))
            self._progressBar:setPercent(tmpData.targetExp/tmpData.maxExp * 100)
            self._expText:setString(string_format("%d/%d",tmpData.targetExp, tmpData.maxExp))
        end

        self._stepDatas = nil
        self:unscheduleUpdate()
    end
end

function ClassRef:tick(dt)
    frame = frame + 1
    if frame < frameMax then
        local num = curExp + math.round(frameExp * frame)

        self._progressBar:setPercent(num/maxExp * 100)
        self._expText:setString(string_format("%d/%d",num, maxExp))

    elseif frame == frameMax then

        self._progressBar:setPercent(targetExp/maxExp * 100)
        self._expText:setString(string_format("%d/%d",targetExp, maxExp))

        self:nextStep()
    end
end

function ClassRef:nextStep()
    frame = 0
    maxExp = 0
    self._step = self._step + 1
    if self._step > #self._stepDatas then
        self:stepOver()
        return
    end
    local stepData = self._stepDatas[self._step]
    --srcExp, targetExp, lv, maxExp
    if stepData.maxExp == 0 then
        self:stepOver()
        return
    end

    self._lvText:setString(tostring(stepData.lv))

    curExp = stepData.srcExp
    targetExp = stepData.targetExp
    maxExp = stepData.maxExp

    frameMax = math.ceil((stepData.targetExp - curExp)/maxExp * FRAME_MAX)

    --这一步分出了多少帧
    if frameMax < FRAME_MIN then
        frameMax = FRAME_MIN
    elseif frameMax > FRAME_MAX then
        frameMax = FRAME_MAX
    end
    --这一步算出来每帧添加多少经验
    frameExp = (stepData.targetExp - curExp)/frameMax
end


--花费IMG ,购买XXX，立即解锁XXX
function ClassRef:_setRichTextOnCost()
    if self._coin then
        local imgStr = string.format("%d%s",self._coin:getAmount(),display.getRichTextImgXml(self._coin:getIcon(), 24, 24))
        local str = string_format(L("battlepass_string3"),imgStr)
        local defaults = {
            KEY_FONT_FACE = Res.font,
            KEY_FONT_SIZE = app:isLanguageEN() and 18 or 22,
            KEY_FONT_COLOR_STRING = "#FFE184",
        }

        --conText为中间下面的文本描述
        local richText = ccui.RichText:createWithXML( str, defaults )
        richText:setAnchorPoint(self._tips2:getAnchorPoint())
        richText:ignoreContentAdaptWithSize(false)
        richText:setContentSize(600,24)
        richText:formatText()
        local f_size = richText:getFormatSize()
        richText:setContentSize(f_size)
        richText:setAnchorPoint(self._tips2:getAnchorPoint())
        richText:setPosition(self._tips2:getPosition())
        richText:addTo(self._tips2:getParent())
        self._tips2:removeFromParent()
        self._tips2 = richText
    end
end

--显示货币的tips
function ClassRef:_showMoneyTips()
    --local coinId = Enums.lootType.starCoin
    if self._coin then
        self:showPanelTips(self._ui.Panel_money,{tipsType = Enums.TipsType.item, itemId = self._coin:getId()})
    end

end

function ClassRef:showPanelTips(panel, param)
    local boundingBoxTemp = panel:getBoundingBox()
    local worldPosTemp = panel:getParent():convertToWorldSpace( cc.p( boundingBoxTemp.x, boundingBoxTemp.y ) )
    boundingBoxTemp.x = worldPosTemp.x
    boundingBoxTemp.y = worldPosTemp.y
    param.boundingBox = boundingBoxTemp
    app:dispatchCustomEvent("EVENT_OPEN_FLOAT", {params = param})
end

--虽然新添加了货币类型 但是事实上从背包中寻找道具数量
function ClassRef:initMoneyPanel(item)
    self._ui.Panel_money:findChild("icon"):loadTexture(item:getIcon())
    self._ui.Panel_money:findChild("num"):setString(tostring(UD:getItemAmountByTid(item:getId())))
end

return ClassRef
